/**
 * @description 商品详情
 */
import style from './styles/Detail.less';
import classnames from "classnames";
import React from 'react';
import EntryBase from "../Common/EntryBase";
const Fragment = React.Fragment;
import { Button, Toast } from 'wd-mobile';
import { detail, isCollect, unCollect, collect, bookGoods, unBookGoods } from "api_liuhaojie/app/goods";
import { query_tips } from "api_xukaiyu/app/content";
import { list } from "api_zhoujianyi/front/app/trade/coupon";
import { preVerify } from "api_zhoujianyi/front/app/trade/purchase";
import { isLogin } from "api_xukaiyu/app/login";

import wxShare from "commons/wxShare";
import util from "commons/util";

let query = util.parseQueryString();

import icon_minus from "images/icon/minus.png";
import icon_plus from "images/icon/plus.png";
import icon_like from "images/icon/like.png";
import icon_like_active from "images/icon/like_active.png";
import icon_home from "images/icon/home.png";

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            countNum: 1, // 购买量
            detail: {},
            isCollect: false, // 是否收藏
            query_tips: "", // 温馨提示
            canUse: [],
            isLogin: false
        }
    }
    componentDidMount() {
        // 查询商品详情
        detail({
            skuId: this.props.match.params.goodsId
        }).then(res => {
            this.setState({
                detail: res.data
            })

            this.getRedList({ tradeAmount: res.data.price, goodsType: res.data.id });

            // 设置分享到商品
            let shareData = {};
            let pathNameArr = location.pathname.split("/");
            pathNameArr.pop();
            shareData.link = location.origin + pathNameArr.join("/") + "/goods.html" + `#/Detail/${res.data.id}`;
            shareData.title = `在吗？给你推荐${res.data.skuName}`;
            shareData.desc = `${res.data.skuName}已售${res.data.soldNum}件，库存不多，悄悄分享给你`;
            shareData.imgUrl = res.data.goodsIcon;
            wxShare(shareData);
        })

        // 查询是否收藏
        isCollect({
            skuId: this.props.match.params.goodsId
        }).then(res => {
            this.setState({
                isCollect: !!res.data
            })
        })

        // 查询温馨提示
        query_tips().then(res => {
            this.setState({
                query_tips: res.data
            })
        })
    }

    //红包列表数据
    getRedList(info) {
        isLogin().then(() => {
            list(info).then(data => {
                this.setState({
                    canUse: data.data || [],
                    isLogin: true
                })
            })
        }, () => {
            this.setState({
                isLogin: false,
                canUse: []
            })
        })
    }

    render() {
        const { canUse, isLogin, detail } = this.state;
        return (
            <Fragment>
                <div className={classnames(style.main, "x-scroll-y")}>
                    <div className={style.home} onClick={() => {
                        location.href = "./index.html"
                    }}>
                        返回首页
                    </div>
                    <div className={style.kv}>
                        <div className={style.goodsLogo} style={this.state.detail.goodsIcon ? { backgroundImage: `url(${this.state.detail.goodsIcon})` } : null}></div>
                        <div className={style.goodsNameAndTag}>
                            <div className={style.goodsName}>{this.state.detail.skuName}</div>
                            <div className={style.goodsTag}>
                                {
                                    this.state.detail.isNoob == 1 && <div className={style.goodsTagNewer}>新人专享</div>
                                }
                                <span>限购{this.state.detail.limitBuyNum}件</span>
                            </div>
                        </div>
                    </div>
                    <div className={style.goodsInfo}>
                        <div className={style.price}>
                            <span className={style.currentPrice}>￥{this.state.detail.price}</span>
                            <span className={style.originPrice}>￥{this.state.detail.recommendPrice}</span>
                        </div>
                        <div className={style.sold}>
                            <div className={style.soldBar}>
                                <div className={style.soldBarBg} style={{ width: this.state.detail.stockNum >= 100 ? "0%" : (100 - this.state.detail.stockNum) + "%" }}></div>
                                <div className={style.soldBarValue}>{this.state.detail.stockNum > 100 ? "库存充足" : (this.state.detail.stockNum > 0 ? `库存 ${this.state.detail.stockNum}件` : "售罄")}</div>
                            </div>
                            <div className={style.soldNum}><span>累计已售{this.state.detail.soldNum}件</span></div>
                        </div>
                    </div>
                    <div className={style.describe}>
                        <div className={style.describePart}>
                            <div className={style.describePartTitle}>
                                商品详情
                            </div>
                            <div className={style.describePartContent} dangerouslySetInnerHTML={{ __html: this.state.detail.instructions }}></div>
                        </div>
                        <div className={style.describePart}>
                            <div className={style.describePartTitle}>
                                温馨提示
                            </div>
                            <div className={style.describePartContent} dangerouslySetInnerHTML={{ __html: util.replaceUrl(this.state.query_tips) || "" }}>
                            </div>
                        </div>
                    </div>
                </div>
                <div className={style.buyBar}>
                    <div className={style.count}>
                        <div className={style.countPrice}>
                            <div className={style.goodsName}>{this.state.detail.skuName}</div>
                            <div className={style.goodsPrice}>
                                <span className={style.goodsPriceTitle}>合计：</span>
                                <span className={style.goodsPriceValue}>¥ {util.Mul(this.state.detail.price || 0, this.state.countNum)}</span>
                            </div>
                        </div>
                        <div className={style.countTool}>
                            <img src={icon_minus} onClick={() => {
                                this.setState({
                                    countNum: this.state.countNum > 1 ? this.state.countNum - 1 : 1
                                })
                            }} alt="" />
                            <span className={style.countNum}>{this.state.countNum}</span>
                            <img src={icon_plus} onClick={() => {
                                // 如果超过限制数量，提示
                                if (this.state.countNum >= this.state.detail.limitBuyNum) {
                                    Toast.info("超出限购", 1000);
                                    return;
                                }
                                this.setState({
                                    countNum: this.state.countNum + 1
                                }, () => {
                                    this.getRedList({ tradeAmount: util.Mul(this.state.detail.price || 0, this.state.countNum), goodsType: this.state.detail.id });
                                })
                            }} alt="" />
                        </div>
                    </div>
                    <div className={style.redPacket}>
                        {!isLogin ? <div className={style.redNum}><span>登陆后查看可用红包</span></div>
                            : !canUse.length && isLogin ? <div className={style.redNum}><span>暂无可用</span></div> : <div className={style.redNum}>支付时有<span>{canUse.length}个红包</span>可用</div>}
                        <div className={style.name}>红包</div>
                    </div>
                    <div className={style.buyButtons}>
                        <div className={style.like} onClick={() => {
                            if (!!this.state.isCollect) {
                                this.unCollect();
                            } else {
                                this.toCollect();
                            }
                        }}>
                            <img src={this.state.isCollect ? icon_like_active : icon_like} alt="" />
                            <span>{this.state.isCollect ? "已收藏" : "收藏"}</span>
                        </div>

                        <Button className={classnames(style.toBuy, {
                            [style.orderStateGray]: (this.state.detail.stockNum <= 0 || !this.state.detail.saleStatus) && !!this.state.detail.isSeckill,
                            [style.seckillSoldOut]: this.state.detail.stockNum <= 0 && !this.state.detail.isSeckill
                        })} onClick={() => {
                            // 如果是秒杀商品，库存小于1或者不在销售状态
                            if ((this.state.detail.stockNum <= 0 || !this.state.detail.saleStatus) && !!this.state.detail.isSeckill) {
                                return;
                            }
                            if (this.state.detail.stockNum > 0) {
                                this.purchase();

                            }
                            if (this.state.detail.stockNum <= 0 && !this.state.detail.isSeckill) {
                                // 预约
                                if (!this.state.detail.isBook) {
                                    bookGoods({
                                        skuId: this.state.detail.id
                                    }).then(res => {
                                        const newDetail = { ...this.state.detail };
                                        newDetail.isBook = true;
                                        this.setState({
                                            detail: newDetail
                                        })
                                        Toast.info("预约成功", 1500);
                                    })
                                } else {
                                    unBookGoods({
                                        skuId: this.state.detail.id
                                    }).then(res => {
                                        const newDetail = { ...this.state.detail };
                                        newDetail.isBook = false;
                                        this.setState({
                                            detail: newDetail
                                        })
                                        Toast.info("已取消预约", 1500);
                                    })
                                }
                            }
                        }}>
                            {
                                !!this.state.detail.isSeckill && (!!this.state.detail.saleStatus ? (this.state.detail.stockNum > 0 ? "立即购买" : "已抢光") : "未开始")
                            }
                            {/* {
                                !this.state.detail.isSeckill && (this.state.detail.stockNum > 0 ? "立即购买" : (!!this.state.detail.isBook ? "已预约" : "预约"))
                                
                            } */}
                            { !this.state.detail.isSeckill && this.state.detail.stockNum > 0 ? "立即购买" : "" }
                            { !this.state.detail.isSeckill && this.state.detail.stockNum <= 0 && !!this.state.detail.isBook ? "已预约" : "" }
                            { !this.state.detail.isSeckill && this.state.detail.stockNum <= 0 && !this.state.detail.isBook ? "预约" : "" }
                        </Button>
                    </div>
                </div>
            </Fragment>
        )
    }

    // 收藏
    toCollect() {
        collect({
            skuId: this.props.match.params.goodsId
        }).then(res => {
            this.setState({
                isCollect: true
            })
        })
    }

    // 取消收藏
    unCollect() {
        unCollect({
            skuId: this.props.match.params.goodsId
        }).then(res => {
            this.setState({
                isCollect: false
            })
        })
    }

    // 购买
    purchase() {
        Toast.loading("", 50000);
        preVerify({
            tradeAmount: (+this.state.detail.price) * this.state.countNum,
            quantity: this.state.countNum,
            origin: "H5",
            goodsType: this.props.match.params.goodsId,
            requestNo: util.uuid()
        }).then(res => {
            Toast.destroy();
            location.href = `./goods.html?purchase=${this.state.countNum}#/Pay/${this.props.match.params.goodsId}`;
        })
    }
}

export default App;